<?php

namespace app\common\command\modelcreater;

use think\facade\Db;

class ModelCreater extends Base
{
    public static function start()
    {
        $tableList = Db::query("show tables");
        foreach ($tableList as $table) {
            foreach ($table as $key => $name) {
                self::writeln($name);
                self::createTableModel($name);
            }
        }

    }

    protected static function createTableModel($tableName)
    {
        self::writeln("=========begein createTableModel===========");
        $tableModelMaker = new TableModelMaker();
        $tableNameCamel = self::snakeToCamel($tableName);
        $tableModelMaker->tableName = $tableNameCamel;

        //获取mysql表的信息
        $tableInfo = Db::query("show table status like '" . $tableName . "'");
        $tableRemark = $tableInfo[0] ? $tableInfo[0]['Comment'] : "";
        $tableModelMaker->tableRemark = $tableRemark;
        //获取mysql表的列信息
        $tableColumnList = Db::query("show full columns from " . $tableName);
        $tableModelMaker->columns = $tableColumnList;

        foreach ($tableColumnList as $key => $column) {
            //判断有没有包含软删除
            if (strtolower($column['Field']) == 'delete_time') {
                $tableModelMaker->isSoftDelete = true;
                $tableModelMaker->softDeleteColumn = $column['Field'];
            }
        }

        self::writeln($tableModelMaker->getCode());
        File::write($tableModelMaker->getFilePath(), $tableModelMaker->getCode());

        self::writeln("=======end createTableModel======");
    }

    private static function snakeToCamel($str)
    {
        $words = explode('_', strtolower($str)); // 首先将字符串按下划线分割并全部小写化

        foreach ($words as &$word) {
            $word = ucfirst(trim($word)); // 对每个单词进行首字母大写处理
        }

        return implode('', $words); // 返回连接后的结果

    }
}